package controller;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.HashMap;

import DAO.DatabasePool;
import DAO.FTRelationTimeDAO;


import model.ConnectionProperty;
import model.FTRelationTime;
import rdbms.RDBMSFTConceptTimeDAO;
import rdbms.RDBMSFTRelationTimeDAO;

public class Job implements Serializable {

	private static final long serialVersionUID = 1L;
	HashMap<String, Term> map = null;
	Term source;
	int date;
	double d = 50000000000L;

	Job(Term source, Object object, int date) {
		this.map = (HashMap<String, Term>) object;
		this.source = source;
		this.date = date;
	}

	public HashMap<String, Term> getMap() {
		return map;
	}

	public int getDate() {
		return date;
	}

	public Term getSource() {
		return source;
	}

	public void setSource(Term source) {
		this.source = source;
	}

	public void execute(){
		//System.out.println("Tamanho " + map.size());
		Search search = new Search();

			ConnectionProperty conn;
			String dbId = "";
			String jobId = "FT_Relation_Time";
			String connectionId = "3";

			conn = new ConnectionProperty(jobId, connectionId,
					TestUtil.Drivers.POSTGRE.getDriver(),
					TestUtil.Drivers.POSTGRE.getUrl(),
					TestUtil.Drivers.POSTGRE.getUser(),
					TestUtil.Drivers.POSTGRE.getPassword(),
					TestUtil.Drivers.POSTGRE.getSchema());
			try {
				
			RDBMSFTRelationTimeDAO rtDAO = new RDBMSFTRelationTimeDAO(conn);
			
			for (String key : map.keySet()) {
				long a = search.generateFrequency(source.getDescription(), map.get(key).getDescription());
				long b = map.get(key).getFrequency();
				long c = source.getFrequency();
				d = d-(a+b+c);
				double result = this.phiSquare(a, b, c, d);
								
				if(result < 0.00001){result = 0.00001;}
				
				rtDAO.insert(new FTRelationTime(source.getId(), map.get(key).getId(), 1, this.date, result, 0, a));
				
			}
			} catch (Exception e) {
				System.out.println("Erro ao exercutar Job");
				e.printStackTrace();
			}
		}
	

	public double phiSquare(final double a, final double b,
			final double c, final double d) throws Exception {
		return (Math.pow((a * d) - (b * c), 2.0))
				/ ((a + b) * (a + c) * (b + d) * (c + d));
	}

}
